package day04;

import javax.print.attribute.standard.Finishings;
import java.io.BufferedReader;
import java.io.FileInputStream;
import java.io.InputStreamReader;
import java.nio.charset.StandardCharsets;
import java.util.ArrayList;
import java.util.Collections;
import java.util.HashMap;
import java.util.Map;

public class Demo09 {
    /*
     * 统计一个小说中每个中文出现的次数
     */
    public static void main(String[] args) throws Exception{
        String file = "F:/《遮天》.txt";
        HashMap<Character, Integer> counter = new HashMap<>();
        BufferedReader in = new BufferedReader(
                new InputStreamReader(new FileInputStream(file),
                        StandardCharsets.UTF_8)
        );
        int ch;
        //4E00-9FA5
        while ((ch = in.read())!=-1){
            char c = (char)ch;
            if(c>='\u4e00' && c<='\u9fa5'){
                Integer n = counter.get(c);
                if (n == null){
                    counter.put(c, 1);
                }else{
                    counter.put(c, n+1);
                }
            }
        }
        in.close();
        System.out.println(counter.size());
        System.out.println(counter);
        //将Map集合中全部的数据(Entry) 转移到List集合, 方便排序
        ArrayList<Map.Entry<Character, Integer>> list = new ArrayList<>();
        list.addAll(counter.entrySet());
        //排序, 对list集合, 根据每个元素的 value 值排序
        Collections.sort(list, (o1, o2)->o2.getValue()-o1.getValue());
        System.out.println(list);
    }
}
